/**
 * ReadWriteLock演示
 *
 * @author fireway
 * @since 2019年 04月 23日 星期二 06:42:36 CST
 */
package concurrency;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReaderWriterList<T> {
    private ArrayList<T> mLockedList;

    /**
     * Make the ordering fair
     */
    private ReentrantReadWriteLock mLock = new ReentrantReadWriteLock(true);

    public ReaderWriterList(int size, T initialValue) {
        mLockedList = new ArrayList<T>(Collections.nCopies(size, initialValue));
    }

    public T get(int index) {
        Lock rlock = mLock.readLock();
        rlock.lock();
        try {
            // Show that multiple readers
            // may acquire the read lock
            if (mLock.getReadLockCount() > 1) {
                System.out.println(mLock.getReadLockCount());
            }
            return mLockedList.get(index);
        } finally {
            rlock.unlock();
        }
    }

    public T set(int index, T element) {
        Lock wlock = mLock.writeLock();
        wlock.lock();
        try {
            return mLockedList.set(index, element);
        } finally {
            wlock.unlock();
        }
    }

    public static void main(String[] args) {
        new ReaderWriterListTest(30, 1);
    }
}
